import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/store'
import Login from '@/components/Login'
import HelloWorld from '@/components/HelloWorld'
import Index from '@/components/Index'
import Form from '@/components/Form'
import TestPage from '@/components/TestPage'

Vue.use(Router)

let beforeEnter = (to, from, next) => {
  let userInfo = window.localStorage.getItem("userInfo");
  if (userInfo == null) {
    store.commit('hideLoading')
    store.commit('showToast', '请先登录')
    next({
      path: '/',
      query: { redirect: to.fullPath}
    })
  } else {
    next()
  }
}

// 增强原方法，增加回退标记
Router.prototype.go = function () {
  this.isBack = true
  window.history.go(-1)
}

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/helloWorld',
      name: 'HelloWorld',
      component: HelloWorld,
      beforeEnter: beforeEnter
    },
    {
      path: '/index',
      name: 'Index',
      component: Index,
      beforeEnter: beforeEnter
    },
    {
      path: '/form',
      name: 'Form',
      component: Form,
      beforeEnter: beforeEnter
    },
    {
      path: '/testPage',
      name: 'TestPage',
      component: TestPage,
      beforeEnter: beforeEnter
    }
  ]
})

router.beforeEach(function (to, from, next) {
  store.commit('showLoading', '加载中')
  next()
})

router.afterEach(function (to) {
  store.commit('hideLoading')
})

export default router
